from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
import uuid

from db.models import MtasksTask  
from schemas.task import TaskCreate, TaskUpdate

class TaskService:
    @staticmethod
    def get_task(db: Session, task_id: str) -> Optional[MtasksTask]:
        return db.query(MtasksTask).filter(MtasksTask.id == task_id).first()

    @staticmethod
    def get_tasks(db: Session, limit: int = 100) -> List[MtasksTask]:
        return db.query(MtasksTask).limit(limit).all()

    @staticmethod
    def create_task(db: Session, task: TaskCreate) -> MtasksTask:
        db_task = MtasksTask(
            id=str(uuid.uuid4()),
            **task.model_dump(),
            createdAt=datetime.utcnow().isoformat()
        )
        db.add(db_task)
        db.commit()
        db.refresh(db_task)
        return db_task

    @staticmethod
    def update_task(db: Session, task_id: str, task: TaskUpdate) -> Optional[MtasksTask]:
        db_task = TaskService.get_task(db, task_id)
        if not db_task:
            return None
        
        update_data = task.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_task, field, value)
        
        db.commit()
        db.refresh(db_task)
        return db_task

    @staticmethod
    def delete_task(db: Session, task_id: str) -> bool:
        db_task = TaskService.get_task(db, task_id)
        if not db_task:
            return False
        
        db.delete(db_task)
        db.commit()
        return True 